<script setup lang="ts">
import { ref, watch, PropType, onMounted, nextTick } from 'vue';
import type { ISocketMessage } from '../../type';

const props = defineProps({
	// 聊天列表
	messageList: {
		type: Array as PropType<ISocketMessage[]>,
		required: true,
		default: () => [],
	},
});

// 消息列表ref
const messageRef = ref<HTMLElement>();
// 禁止滚动
const prohibitScroll = ref<boolean>(false);

// 滚动到底部
const handleScrollBottom = () => {
	if (!messageRef.value || prohibitScroll.value) return;
	messageRef.value.scrollTop = messageRef.value.scrollHeight;
};

// 滚动事件
const onOrderScroll = (event: UIEvent) => {
	const dom = event.target as HTMLElement;
	// 距离顶部的距离
	const scrollTop = Math.ceil(dom.scrollTop);
	// 可视区高度
	const domHeight = dom.clientHeight;
	// 滚动条总高度
	const scrollHeight = dom.scrollHeight;
	// 把距离顶部的距离加上可视区域的高度 等于或者大于滚动条的总高度就是到达底部
	if (scrollTop + domHeight >= scrollHeight) {
		if (!prohibitScroll.value) return;
		prohibitScroll.value = false;
	} else {
		if (prohibitScroll.value) return;
		prohibitScroll.value = true;
	}
};

// 点击返回底部
const clickReturnBottom = () => {
	prohibitScroll.value = false;
	handleScrollBottom();
};

watch(
	() => props.messageList,
	() => {
		nextTick(() => {
			handleScrollBottom();
		});
	},
	{
		deep: true,
	}
);

onMounted(() => {
	nextTick(() => {
		handleScrollBottom();
	});
});
</script>

<template>
	<div ref="messageRef" class="chat-message" @scroll="onOrderScroll">
		<div v-if="prohibitScroll" class="return-to-bottom" @click="clickReturnBottom">返回底部</div>
		<transition-group tag="ul" name="msg">
			<template v-for="(msg, i) in messageList" :key="i">
				<li v-if="msg.type" class="right">
					<div class="avatar">
						{{ msg.name }}
						<img :src="msg.avatar" />
					</div>
					<div class="msg">
						<div class="msg-item">
							{{ msg.msg }}
						</div>
					</div>
				</li>
				<li v-else class="left">
					<div class="avatar">
						<img :src="msg.avatar" />
						{{ msg.name }}
					</div>
					<div class="msg">
						{{ msg.msg }}
					</div>
				</li>
			</template>
		</transition-group>
	</div>
</template>

<style lang="less" scoped>
@import url('./index.less');
</style>
